package com.jucai.pppeiyouclient.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jucai.pppeiyouclient.MainActivity;
import com.jucai.pppeiyouclient.R;
import com.jucai.pppeiyouclient.base.BaseActivity;
import com.jucai.pppeiyouclient.comm.CommonData;
import com.jucai.pppeiyouclient.comm.CommonRequestNetData;
import com.jucai.pppeiyouclient.utils.ActivityCollector;
import com.jucai.pppeiyouclient.utils.CommonUtil;
import com.jucai.pppeiyouclient.utils.LogUtils;
import com.jucai.pppeiyouclient.utils.LoginUtils;
import com.jucai.pppeiyouclient.utils.SharedPreferencesUtil;
import com.jucai.pppeiyouclient.utils.ToastUtils;
import com.jucai.pppeiyouclient.weidget.GetVerTextView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import io.rong.imkit.RongIM;
import io.rong.imlib.RongIMClient;
import io.rong.imlib.model.UserInfo;

import static com.jucai.pppeiyouclient.R.id.forget_submit;

public class ForgetPassActivity extends BaseActivity {
    private static final String TAG = "ForgetPassActivity : ";
    private EditText forgetPhone, forgetVer, forgetNewPass;
    private TextView forgetSubmit;
    private GetVerTextView forgetGetVer;
    private String empty;
    private Handler mHandler = new Handler();

    @Override
    protected void initView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_forget_pass);

        ((TextView) findViewById(R.id.common_title_text)).setText("找回密码");

        forgetPhone = (EditText) findViewById(R.id.forget_phone);
        forgetVer = (EditText) findViewById(R.id.forget_ver);
        forgetNewPass = (EditText) findViewById(R.id.forget_new_pass);
        forgetGetVer = (GetVerTextView) findViewById(R.id.forget_get_ver);
        forgetSubmit = (TextView) findViewById(forget_submit);
    }

    @Override
    protected void initData() {
        forgetPhone.setSingleLine();
        forgetVer.setSingleLine();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void loadNetData() {

    }

    @Override
    protected void setListener() {
        findViewById(R.id.common_back).setOnClickListener(this);
        findViewById(R.id.common_home_back).setOnClickListener(this);
        forgetGetVer.setOnClickListener(this);
        forgetSubmit.setOnClickListener(this);
    }

    private String judgeEmpty() {
        if (TextUtils.isEmpty(forgetPhone.getText().toString())) {
            return "手机号不能为空";
        } else if (TextUtils.isEmpty(forgetVer.getText().toString())) {
            return "验证码不能为空";
        } else if (TextUtils.isEmpty(forgetNewPass.getText().toString())) {
            return "请设置新密码";
        } else if(forgetNewPass.length()<8){
            return "新密码不小于八位";
        }else{
            return "";
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.common_back:
                ActivityCollector.removeActivity(this);
                break;

            case R.id.common_home_back:
                startActivity(new Intent(ForgetPassActivity.this, MainActivity.class));
                ActivityCollector.removeActivity(this);
                break;

            case R.id.forget_get_ver:
                if (TextUtils.isEmpty(forgetPhone.getText().toString())) {
                    ToastUtils.showToast("请输入手机号");
                } else if (forgetGetVer.getIsHandler()) {
                    return;
                } else {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("service", "Public_VerifyCode.SendResetPwCode");
                    param.put("member_phone", forgetPhone.getText().toString());
                    CommonRequestNetData.getJsonStringData(ForgetPassActivity.this, param, true, new CommonRequestNetData.JsonStringCallBack() {
                        @Override
                        public void parseJsonString(String str) {
                            LogUtils.e(TAG + "str = " + str);
                            ToastUtils.showToast(str);
                            if (!TextUtils.equals(str,"该手机号码未注册")) {
                                forgetGetVer.setHandler();
                            }
                        }
                    });
                }
                break;

            case forget_submit:
                CommonUtil.hideSoftInput(forgetNewPass);
                empty = judgeEmpty();
                if (TextUtils.equals("", empty)) {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("service", "Client_UpdatePassword.go");
                    param.put("member_phone", forgetPhone.getText().toString());
                    param.put("verifycode", forgetVer.getText().toString());
                    param.put("password", forgetNewPass.getText().toString());
                    CommonRequestNetData.getJsonStringData(ForgetPassActivity.this, param, true, new CommonRequestNetData.JsonStringCallBack() {
                        @Override
                        public void parseJsonString(String str) {
                            LogUtils.e(TAG + "str = " + str);
                            Toast.makeText(ForgetPassActivity.this, "修改成功，3s后为您自动跳转登录", Toast.LENGTH_LONG).show();
                            mHandler.postDelayed(new jumpMain(), 3000);
                        }
                    });
                } else {
                    ToastUtils.showToast(empty);
                }
                break;

            default:
                break;
        }
    }

    class jumpMain implements Runnable {
        @Override
        public void run() {

            HashMap<String, String> param = new HashMap<>();
            param.put("service", "Accompany_Login.go");
            param.put("member_phone", forgetPhone.getText().toString());
            param.put("password", forgetNewPass.getText().toString());
            param.put("jpush_regid", SharedPreferencesUtil.getStringPreference(ForgetPassActivity.this, "j_push", "registration_id", ""));
            LogUtils.e(TAG + "param = " + param);

            CommonRequestNetData.getJsonObjectData(ForgetPassActivity.this, param, true, new CommonRequestNetData.JsonObjectCallBack() {
                @Override
                public void parseJsonObject(JSONObject jsonObject) {
                    LogUtils.e(TAG + "jsObj = " + jsonObject.toString());
                    try {
                        String token = jsonObject.getString("token");
                        String memberId = jsonObject.getString("member_id");
                        String rongyun_token = jsonObject.getString("rongyun_token");

                        final String rongyun_avatar = jsonObject.getString("rongyun_avatar");
                        final String rongyun_nickname = jsonObject.getString("rongyun_nickname");
                        RongIM.connect(rongyun_token, new RongIMClient.ConnectCallback() {
                            @Override
                            public void onTokenIncorrect() {
                                LogUtils.e("onTokenIncorrect");
                            }

                            @Override
                            public void onSuccess(String userId) {
                                LogUtils.e("onSuccess:" + userId);
                                LoginUtils.saveRongyun_id(ForgetPassActivity.this,userId);
                                final UserInfo info = new UserInfo(userId, rongyun_nickname, Uri.parse(rongyun_avatar));
                                RongIM.setUserInfoProvider(new RongIM.UserInfoProvider() {

                                    @Override
                                    public UserInfo getUserInfo(String userId) {
                                        return info;
                                    }

                                }, true);
                                RongIM.getInstance().setCurrentUserInfo(info);
                            }

                            @Override
                            public void onError(RongIMClient.ErrorCode errorCode) {
                                LogUtils.e("onError:" + errorCode.getMessage());
                            }
                        });

                        LogUtils.e(TAG + "token = " + token + " , memberId = " + memberId + ",rongyun_token:" + rongyun_token);
                        CommonData.saveLoginData(ForgetPassActivity.this, memberId, forgetPhone.getText().toString(), token, rongyun_token);
                        ToastUtils.showToast("登录成功");
                        startActivity(new Intent(ForgetPassActivity.this, MainActivity.class));
                        ActivityCollector.removeActivity(ForgetPassActivity.this);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
}
